<template>
  <div class="tooltip" ref="tooltipContainer" v-if="props.visible" :style="styleObject">
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue'
const props = defineProps({
  visible: Boolean,
  location: Object | Array
})
const emit = defineEmits(['update:visible'])

const tooltipContainer = ref(null)

const styleObject = computed(() => {
  return {
    left: (props?.location?.x || props?.location?.[0] || 0) + 8 + 'px',
    top: (props?.location?.y || props?.location?.[1] || 0) + 8 + 'px'
  }
})

const handleClose = (e) => {
  if(props.visible && !tooltipContainer.value?.contains?.(e?.target)) {
    emit('update:visible',false);
  }
}

watchEffect(() => {
  if (props.visible) {
    document.addEventListener('click', handleClose)
  } else {
    document.removeEventListener('click', handleClose)
  }
  return () => {
    document.removeEventListener('click', handleClose)
  }
})
</script>

<style lang="less" scoped>
.tooltip {
  padding: 8px;
  max-width: 200px;
  max-height: 280px;
  background: #ffffff;
  box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  border: 1px solid #c9cdd4;
  overflow: auto;
  position: absolute;
}
</style>
